package com.lydms.service.impl;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lydms.service.TranslateService;
import com.lydms.thirdparty.Mai;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service
public class TranslateServiceImpl implements TranslateService {
    private static final Logger logger = LogManager.getLogger(TranslateServiceImpl.class);

    //  注入百度翻译。
    @Autowired
    private Mai translate;

    /**
     * 翻译
     *
     * @param chinese
     * @return
     */
    @Override
    public String translate(String chinese, String transPort) {

//        1、调用百度翻译
        String result = this.translate.fanyi(chinese, transPort);
        logger.info("调用百度翻译以后的结果为 :{}", result);

//        2、对接收的返回值进行处理
        List<Map> transResult = null;
        Map json = null;
        ObjectMapper mapper = new ObjectMapper();
        try {
//            获取返回值
            json = mapper.readValue(result, Map.class);
            transResult = (List) json.get("trans_result");
            if (transResult == null) {
//                获取状态码
                int error = Integer.parseInt(json.get("error_code").toString());
                logger.info("翻译的异常,状态码为：{}", error);
                return null;
            }
        } catch (Exception e) {
            logger.info("结果集合转换json格式出现问题" + result);
        }
        String after = null;

//        3、获取其中的返回值
        try {
            after = transResult.get(0).get("dst").toString();
        } catch (Exception e) {
            logger.info("调用翻译后无返回值");
            return null;
        }
        logger.info("翻译以后的值为" + after);
        return after;
    }


}
